package td3.model;

import java.awt.datatransfer.Transferable;
import java.io.File;
import java.util.List;

import javax.swing.JComponent;
import javax.swing.TransferHandler;
import javax.swing.tree.TreeNode;

public class ContactFileTransferHandler extends TransferHandler {

	private static final long serialVersionUID = 8807026538766261644L;

	private final AppModel appModel;

	public ContactFileTransferHandler(final AppModel appModel) {
		this.appModel = appModel;
	}

	@Override
	public boolean importData(TransferSupport support) {
		if (canImport(support)) {
			try {
				Transferable t = support.getTransferable();
				List<?> contactsFiles = (List<?>) t
						.getTransferData(ContactFileTransferable.contactsFileFlavor);
				if (contactsFiles == null || contactsFiles != null
						&& contactsFiles.size() != 1)
					return false;
				try {
					appModel.setCurrentFile((File) contactsFiles.get(0));
					TreeNode root = ContactTreeModel.openXMLContacts(
							(File) contactsFiles.get(0),
							appModel.getContactTreeModel());
					appModel.getContactTreeModel().setRoot(root);

				} catch (Exception e) {
					System.out.println("Error while parsing file");
				}
				return true;
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return false;
	}

	@Override
	public int getSourceActions(JComponent component) {
		return TransferHandler.MOVE;// COPY MOVE LINK

	}

	//
	// @Override
	// public ContactFileTransferable createTransferable(JComponent c) {
	// File file = null;
	// if (c instanceof JPanel) {
	// // try {
	// // TreePath path = ((JTree) c).getSelectionPath();
	// // node = (DefaultMutableTreeNode) path.getLastPathComponent();
	// // } catch (Exception e) {
	// // System.err
	// //
	// .println("ContactTransferHanlder.createTransferable(JComponent) FAILED");
	// // e.printStackTrace();
	// // }
	// // return new ContactFileTransferable(node);
	// }
	// return null;
	// }

	@Override
	public boolean canImport(TransferHandler.TransferSupport support) {
		return support.isDrop()
				&& support.getTransferable().isDataFlavorSupported(
						ContactFileTransferable.contactsFileFlavor);
	}

}
